// noinspection JSUnresolvedFunction

import axios from 'axios'

import {Cookies} from "quasar";
import {CONFIG} from "~/utils/conf/index.js";
import router from "~/utils/router/index.js";

import {Notify} from "quasar";

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API, timeout: 99999
})


const headers = () => {
  return {
    'Content-Type': 'application/json', "Authorization": "Bearer " + Cookies.get('access'),
  }
}

service.interceptors.request.use(config => {
  config.headers = {
    ...headers(), ...config.headers,
  }
  return config
})


service.interceptors.response.use(response => {
  return response
}, error => {
  const status = error.response.status
  const msg = error.response.data?.msg?.code
  const url = error.response.config.url
  // 如果TOKEN过期，重新获取TOKEN
  if ((status === 401 && url !== CONFIG.TOEKN_REFRESH_URL && msg === 'token_not_valid') || !Cookies.get('access_half')) {
    const account_store = useAccountStore()
    return account_store.refreshToken(Cookies.get('refresh')).then(resp => {
      error.config.headers['Authorization'] = 'Bearer ' + resp.data.access
      return service(error.config)
    })
  }
  // 如果调用刷新TOKEN接口，返回错误则重新登录,如果是其他接口，提示错误信息
  if (url !== CONFIG.TOKEN_REFRESH_URL) {
    Notify.create({
      type: 'warning',
      message: error.response.data.msg !== undefined ? error.response.data.msg : '系统开小差',
      position: 'top',
      progress: true,
      timeout: 2000,
    })
  } else {
    router.push({name: 'login'}).then()
  }
  return Promise.reject(error)
})


export const request = service


const service_account = axios.create({
  baseURL: import.meta.env.VITE_BASE_API, timeout: 99999
})

service_account.interceptors.request.use(config => {
  config.headers = {
    ...headers(), ...config.headers,
  }
  return config
})

service_account.interceptors.response.use(response => {
  return response
}, error => {
  const status = error.response.status
  const msg = error.response.data?.msg?.code
  const url = error.response.config.url
  // 如果TOKEN过期，重新获取TOKEN
  if (status === 401 && url !== CONFIG.TOEKN_REFRESH_URL && msg === 'token_not_valid') {
    const account_store = useAccountStore()
    return account_store.refreshToken(Cookies.get('refresh')).then(resp => {
      error.config.headers['Authorization'] = 'Bearer ' + resp.data.access
      return service(error.config)
    })
  }
  // 如果调用刷新TOKEN接口，返回错误则重新登录,如果是其他接口，提示错误信息
  if (url !== CONFIG.TOEKN_REFRESH_URL) {
    Notify.create({
      type: 'negative',
      message: error.response.data.msg !== undefined ? error.response.data.msg : '系统开小差',
      position: 'top-right',
      progress: true,
      timeout: 2000,
    })
  } else {
    router.push({name: 'login'}).then()
  }
  return Promise.reject(error)
})

export const request_account = service_account

